package com.elder.business.service.impl;

import java.lang.annotation.Retention;
import java.time.*;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSONObject;
import com.elder.business.domain.ElderlyInfo;
import com.elder.business.domain.MealRecordsDTO;
import com.elder.business.domain.NursingRecords;
import com.elder.business.mapper.ElderlyInfoMapper;
import com.elder.common.core.page.TableDataInfo;
import com.elder.common.utils.DateUtils;
import com.elder.common.utils.LongUtils;
import com.elder.common.utils.StringNewUtils;
import com.elder.common.utils.bean.BeanUtils;
import com.elder.common.utils.uuid.SnowGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.elder.business.mapper.MealRecordsMapper;
import com.elder.business.domain.MealRecords;
import com.elder.business.service.IMealRecordsService;

/**
 * 膳食记录Service业务层处理
 * 
 * @author elder
 * @date 2023-11-26
 */
@Service
public class MealRecordsServiceImpl implements IMealRecordsService 
{
    @Autowired
    private MealRecordsMapper mealRecordsMapper;
    @Autowired
    private ElderlyInfoMapper elderlyInfoMapper;
    /**
     * 查询膳食记录
     * 
     * @param mealId 膳食记录主键
     * @return 膳食记录
     */
    @Override
    public JSONObject selectMealRecordsByMealId(Long mealId)
    {
        MealRecords v = mealRecordsMapper.selectMealRecordsByMealId(mealId);
        JSONObject obj = new JSONObject();
        if(Objects.nonNull(v)) {
            ElderlyInfo elder = elderlyInfoMapper.getElderInfoByElderId(v.getElderId());
            obj.put("mealId", StringNewUtils.long2Str(v.getMealId()));
            obj.put("elderId", StringNewUtils.long2Str(v.getElderId()));
            obj.put("mealTime", DateUtils.dateStrMIAO(v.getMealTime()));
            obj.put("mealType", v.getMealType());
            obj.put("mealUrl", v.getMealUrl());
            obj.put("foodItems", v.getFoodItems());
            obj.put("elderName", elder.getElderName());
            obj.put("carerName",v.getCarerName());
            obj.put("notes", v.getNotes());
        }
        return obj;
    }

    /**
     * 查询膳食记录列表
     * @param elderName
     * @param
     * @param pageNum
     * @param pageSize
     * @return 膳食记录
     */
    @Override
    public TableDataInfo selectMealRecordsList(String elderName,String startTime,String endTime,Integer pageNum,Integer pageSize)
    {
        List<Long> elderIds = null;
        if(!StringNewUtils.isEmpty(elderName)){
            List<ElderlyInfo> elderinfoList = elderlyInfoMapper.getElderinfoList(elderName);
            if(CollectionUtils.isNotEmpty(elderinfoList)){
                elderIds = elderinfoList.stream().map(ElderlyInfo::getElderId).collect(Collectors.toList());
            }
        }
        //用餐时间处理
        Long daystartTime = null;
        Long dayendTime = null;
        if(!StringNewUtils.isEmpty(startTime)&& !StringNewUtils.isEmpty(endTime)){
            Long currentTime = DateUtils.getTargetDateSeconds(startTime);
            daystartTime = getDayStartTime(currentTime);
            dayendTime = getDayEndTime(currentTime);
        }
        //分页
        PageHelper.startPage(pageNum, pageSize);
        List<MealRecords> list = mealRecordsMapper.getMealRecordsList(elderIds,daystartTime,dayendTime);
        PageInfo<MealRecords> pageInfo = new PageInfo<>(list);
        List<MealRecords> mealRecordsList = pageInfo.getList();
        Map<Long, ElderlyInfo> elderlyInfoMap = new HashMap<>();
        if(CollectionUtils.isNotEmpty(mealRecordsList)) {
            List<Long> elderIdList = mealRecordsList.stream().map(MealRecords::getElderId).collect(Collectors.toList());
            List<ElderlyInfo> elderlyInfoList = elderlyInfoMapper.getElderInfoByElderIds(elderIdList);
            elderlyInfoMap = elderlyInfoList.stream().collect(Collectors.toMap(ElderlyInfo::getElderId, Function.identity()));
        }
        TableDataInfo data = new TableDataInfo();
        data.setTotal(pageInfo.getTotal());
        Map<Long, ElderlyInfo> finalElderlyInfoMap = elderlyInfoMap;
        data.setRows(
                mealRecordsList.stream().map(v->{
                    JSONObject obj = new JSONObject();
                    obj.put("mealId", StringNewUtils.long2Str(v.getMealId()));
                    obj.put("elderId", StringNewUtils.long2Str(v.getElderId()));
                    obj.put("mealTime", DateUtils.dateStrMIAO(v.getMealTime()));
                    obj.put("mealType", v.getMealType());
                    obj.put("mealUrl", v.getMealUrl());
                    obj.put("foodItems", v.getFoodItems());
                    obj.put("carerName",v.getCarerName());
                    obj.put("elderName", finalElderlyInfoMap.get(v.getElderId()).getElderName());
                    obj.put("notes", v.getNotes());
                    return obj;
                }).collect(Collectors.toList()));
        return data;
    }

    /**
     * 新增膳食记录
     * 
     * @param mealRecordsDTO 膳食记录
     * @return 结果
     */
    @Override
    public int insertMealRecords(MealRecordsDTO mealRecordsDTO)
    {
        MealRecords mealRecords = new MealRecords();
        BeanUtils.copyProperties(mealRecordsDTO, mealRecords);
        mealRecords.setMealId(SnowGenerator.getId());
        mealRecords.setElderId(LongUtils.str2Long(mealRecordsDTO.getElderId()));
        mealRecords.setMealTime(DateUtils.getDateSeconds(mealRecordsDTO.getMealTime()));
        mealRecords.setCreateTime(DateUtils.getLongTime());
        return mealRecordsMapper.insertMealRecords(mealRecords);
    }

    /**
     * 修改膳食记录
     * 
     * @param mealRecordsDTO 膳食记录
     * @return 结果
     */
    @Override
    public int updateMealRecords(MealRecordsDTO mealRecordsDTO)
    {
        MealRecords mealRecords = new MealRecords();
        BeanUtils.copyProperties(mealRecordsDTO, mealRecords);
        mealRecords.setMealId(LongUtils.str2Long(mealRecordsDTO.getMealId()));
        mealRecords.setElderId(LongUtils.str2Long(mealRecordsDTO.getElderId()));
        mealRecords.setMealTime(DateUtils.getDateSeconds(mealRecordsDTO.getMealTime()));
        mealRecords.setUpdateTime(DateUtils.getLongTime());
        return mealRecordsMapper.updateMealRecords(mealRecords);
    }

    /**
     * 批量删除膳食记录
     * 
     * @param mealIds 需要删除的膳食记录主键
     * @return 结果
     */
    @Override
    public int deleteMealRecordsByMealIds(Long[] mealIds)
    {
        return mealRecordsMapper.deleteMealRecordsByMealIds(mealIds);
    }

    /**
     * 删除膳食记录信息
     * 
     * @param mealId 膳食记录主键
     * @return 结果
     */
    @Override
    public int deleteMealRecordsByMealId(Long mealId)
    {
        return mealRecordsMapper.deleteMealRecordsByMealId(mealId);
    }


    public static Long getCurrentTime(String currentTime) {
        LocalDate date = LocalDate.parse(currentTime);
        LocalDateTime startDate = date.atStartOfDay();
        // 获取时间戳（秒级）
        return startDate.toEpochSecond(ZoneOffset.UTC);
    }

    public static Long getDayStartTime(Long timeSeconds) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date(timeSeconds * 1000));
        //将小时设置成0
        cal.set(Calendar.HOUR_OF_DAY, 0);
        //将分钟设置成0
        cal.set(Calendar.MINUTE, 0);
        //将秒设置成0
        cal.set(Calendar.SECOND, 0);
        //将毫秒至999
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTimeInMillis() / 1000;
    }
    public static Long getDayEndTime(Long timeSeconds) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date(timeSeconds * 1000));
        //将小时设置成0
        cal.set(Calendar.HOUR_OF_DAY, 23);
        //将分钟设置成0
        cal.set(Calendar.MINUTE, 59);
        //将秒设置成0
        cal.set(Calendar.SECOND, 59);
        //将毫秒至999
        cal.set(Calendar.MILLISECOND, 999);
        return cal.getTimeInMillis() / 1000;
    }
}
